package br.com.locadoracom.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import br.com.locadoracom.model.Midia;
import br.com.locadoracom.model.TipoMidia;

public class MidiaDao extends Dao<Midia> {

	EntityManagerFactory  emf = Persistence.createEntityManagerFactory("Locadora");
	EntityManager em = emf.createEntityManager();
	
	@Override
	public void create(Midia midia) {
		em.getTransaction().begin();
		em.persist(midia);
		em.getTransaction().commit();
	}

	@Override
	public Midia merge(Midia midia) {
		Midia temp;
		em.getTransaction().begin();
		temp = em.merge(midia);
		em.getTransaction().commit();
		return temp;
	}

	@Override
	public void remove(Midia midia) {
		em.getTransaction().begin();
		em.remove(midia);
		em.getTransaction().commit();
	}

	@Override
	public Midia findById(Integer Id) {
		return em.find(Midia.class, Id);
	}

	@SuppressWarnings("unchecked")
	public List<Midia> findByAll() throws Exception {
		String strQuery="select m from Midia m";
        Query rsQuery = em.createQuery(strQuery);
		return  rsQuery.getResultList();
	}
	
	public Midia procurarPorTipo(TipoMidia tipo){ 
		Query query = em.createQuery("select m from Midia m where m.tipoMidia=:tipo");
		query.setParameter("tipo", tipo);
		if (query.getResultList().size() == 0)
			return null;
		return (Midia) query.getSingleResult();
	}	
}
